<?php

namespace App\Http\Controllers;

use App\Models\Asset;
use App\Models\AssetBundle;
use App\Models\AssetStock;
use App\Models\Fee\FeeFormula;
use App\Models\FilterableAssetBundle\FilterableAssetBundle;
use App\Models\Order\Order;
use App\Models\Order\OrderItem;
use Artisan;
use Hyn\Tenancy\Environment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DevHelperController extends Controller
{
    /**
     * 重置数据库,保留oauth相关数据表
     * @return \Illuminate\Http\JsonResponse
     */
    public function refreshDB()
    {
        $website = app(Environment::class)->tenant();
        $steps = collect(DB::select('select count(*)-7 as step from migrations'))->first()->step;
        if ($steps <= 0) {
            return "不需要重置";
        }
        $forceResetDB = config('app.enable_developer_console_force_reset_db') ? "--force" : "";
        Artisan::call("tenancy:migrate:refresh $forceResetDB --step=$steps --website_id=$website->id");
        Artisan::call("tenancy:db:seed $forceResetDB --class=RefreshSeeder --website_id=$website->id");
//        Artisan::call("migrate:refresh $forceResetDB --step=$steps");
//        Artisan::call("db:seed $forceResetDB --class=RefreshSeeder");
//        Artisan::call('cache:clear');
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function clearCache()
    {
        Artisan::call('cache:clear');
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock20Assets()
    {
        factory(Asset::class, 20)->create();
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock20AssetStocks()
    {
        factory(AssetStock::class, 20)->create();
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock20AssetBundles()
    {
        factory(AssetBundle::class, 20)->create();
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock20FilterableBundles()
    {
        factory(FilterableAssetBundle::class, 20)->create();
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock10Orders() {
        for($i = 0; $i < 10; ++$i) {
            $order = factory(Order::class)->create();
            $max = random_int(1, 7);
            $loop = range(min(1, $max), max(1, $max));
            foreach ($loop as $idx) {
                $orderItem = factory(OrderItem::class)->create(["order_id" => $order->id]);
            }
            $order->items;
        }
        $result = 'ok';
        return response()->json(compact(['result']));
    }

    public function mock10FeeRules() {
        factory(FeeFormula::class, 10)->create();
        $result = 'ok';
        return response()->json(compact(['result']));
    }
}
